package com.apkcore.handlerlib

import java.util.concurrent.LinkedBlockingQueue

/**
 * @author chanehao
 * @date 2023/03/13
 * @apiNote
 */
class Handler(private val looper: Looper, private val callback: Callback?) {
    interface Callback {
        fun handlerMessage(msg: Message)
    }

    fun sendMessage(msg: Message) {
        msg.target = this
        looper.queue.enqueue(msg)
    }

    fun dispatchMessage(msg: Message) {
        callback?.handlerMessage(msg)
    }
}

class Looper :Runnable{
//    private val sThreadLocal = ThreadLocal<Looper>()
    val queue = MessageQueue()
    private var running = false

//    fun prepare() {
//        sThreadLocal.set(Looper())
//    }
//
//    fun myLooper(): Looper {
//        if (sThreadLocal.get() == null) {
//            throw RuntimeException("Only one Looper may be created per thread");
//        }
//        return sThreadLocal.get()
//    }

    override fun run() {
        running = true
        while (running) {
            val msg = queue.next()
            msg?.target?.dispatchMessage(msg)
        }
    }
    fun start() {
        Thread(this).start()
    }
    fun quit() {
        running = false
    }
}

data class Message(val what: Int = 0, val obj: Any? = null, var target: Handler? = null)

class MessageQueue {
    private val queue = LinkedBlockingQueue<Message>()

    fun enqueue(msg: Message) {
        queue.put(msg)
    }

    fun next(): Message? {
        return try {
            queue.take()
        } catch (e: InterruptedException) {
            null
        }
    }
}